/*
 router.go
 Created by hupfei on 2019-07-17
*/

package service

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/drive/redis"
	. "zimuzu_cvn_web_api/pkg/e"
)

// 获取全网代币总数
func GetGlobalCvnTotal() (total float64, err error) {
	cacheKey := PublicCacheKeyPre + "total"
	if redis.Exists(cacheKey) {
		str, err := redis.Get(cacheKey)
		if err != nil {
			return total, err
		}
		total, err = strconv.ParseFloat(str, 64)
		if err != nil {
			return total, err
		}
		return total, nil
	}

	// 全网账户代币CVN基数
	RouterBaseNum, err := GetGlobalFloat64(GlobalCvnBaseNum)
	if err != nil {
		return 0.00, err
	}

	totalRe, err := model.GetGlobalUserCvn()
	if err != nil {
		return 0.00, err
	}
	total = RouterBaseNum + totalRe.UnWithDrawnCvn + totalRe.PledgingCvn + totalRe.RouterPledgingCvn + totalRe.SuperNodePledgingCvn + totalRe.PCPledgingCvn
	redis.SetUnRe(cacheKey, total, TimeFormatMin*5)
	return total, nil
}

// 获取float64的Global
func GetGlobalFloat64(Key string) (re float64, err error) {

	str, err := model.GetGlobalVar(Key)
	if err != nil {
		return re, err
	}

	re, err = strconv.ParseFloat(str, 64)
	if err != nil {
		return re, err
	}

	return re, nil
}

/*
 * @ Author: hupfei
 * @ Description: 路由器累计贡献流量
 **/
func GetRouterTotalUpload(uid int64, Type int) (upload int64, err error) {
	if Type == model.NodeTypeRouter {
		oldUploadKey := UserRedisPrefix + RedisUserOldUploadKey
		if uid > 0 {
			oldUploadKey += strconv.FormatInt(uid, 10)
		}
		var oldData int64
		if redis.Exists(oldUploadKey) {
			uploadStr, err := redis.Get(oldUploadKey)
			if err != nil {
				Log("err", "redis获取路由器累计贡献失败(老数据)", err.Error())
				return 0, err
			}
			oldData, _ = strconv.ParseInt(uploadStr, 10, 64)
		} else {
			oldData, err = model.GetRouterOldUpload(uid)
			if err != nil {
				return
			}

			_, _ = redis.Set(oldUploadKey, strconv.FormatInt(oldData, 10), -1)
		}

		newData, err := model.GetUserTotalUpload(uid, model.NodeTypeRouter)
		if err != nil {
			return newData, err
		}

		upload = oldData + newData
	} else {
		upload, err = model.GetUserTotalUpload(uid, Type)
	}
	return
}

/*
 * @ Author: hupfei
 * @ Description: 用户路由器累计获得CVNT
 **/
func GetRouterTotalCvnt(uid int64, Type int) (cvnt float64, err error) {
	if Type == model.NodeTypeRouter {
		oldCvntKey := UserRedisPrefix + strconv.FormatInt(uid, 10) + RedisUserOldCvntKey
		var oldData float64
		if redis.Exists(oldCvntKey) {
			uploadStr, err := redis.Get(oldCvntKey)
			if err != nil {
				Log("err", uid, "redis获取用户累计获得CVNT失败(老数据)", err.Error())
				return 0, err
			}
			oldData, _ = strconv.ParseFloat(uploadStr, 64)
		} else {
			oldData, err = model.GetUserOldRouterCvnt(uid)
			if err != nil {
				return
			}

			_, _ = redis.Set(oldCvntKey, strconv.FormatFloat(oldData, 'f', -1, 64), -1)
		}

		newData, err := model.GetUserReceivedCvnt(uid, 1, model.NodeTypeRouter)
		if err != nil {
			return newData, err
		}
		cvnt = oldData + newData
	} else {
		cvnt, err = model.GetUserReceivedCvnt(uid, 1, Type)
		if err != nil {
			return
		}
	}
	cvntStr := fmt.Sprintf("%.8f", cvnt)
	cvnt, _ = strconv.ParseFloat(cvntStr, 64)
	return
}

// 折线图
func GetClientRouterUserData(Uid int64, NodeId, ShowType, nodeType int) (res []model.ChartRouter, err error) {

	hash := Md5Str(strconv.Itoa(NodeId)+strconv.Itoa(ShowType)) + strconv.Itoa(nodeType)
	cacheKey := UserRedisPrefix + strconv.FormatInt(Uid, 10) + OperateNodeData + hash
	if redis.Exists(cacheKey) {
		dataStr, err := redis.Get(cacheKey)
		if err != nil {
			return res, err
		}

		err = json.Unmarshal([]byte(dataStr), &res)
		if err != nil {
			return res, err
		}

		return res, nil
	}

	if ShowType == 1 {
		//时报表
		t := time.Now()
		//当日零点时间戳
		zeroTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).Unix()
		for i := 0; i <= t.Hour(); i++ {
			chart := model.ChartRouter{
				Time:        time.Unix(zeroTime+int64(60*60*i), 0).Format("2006/01/02 15:04"),
				Total:       "0",
				TotalFormat: "0",
			}
			res = append(res, chart)
		}

		list, err := model.GetClientRouterUserData(NodeId, ShowType, nodeType)
		if err != nil {
			return res, err
		}
		for index, chart := range res {
			for _, v := range list {
				if v.Time == chart.Time {
					totalFloat, _ := strconv.ParseFloat(v.Total, 64)
					res[index].Total = strconv.FormatFloat(totalFloat, 'f', -1, 64)
					res[index].TotalFormat = SizeFormat(totalFloat*1024, 2)
				}
			}
		}
	} else {
		res, err = model.GetClientRouterUserData(NodeId, ShowType, nodeType)
		if err != nil {
			return res, err
		}
		for index, chart := range res {
			totalFloat, _ := strconv.ParseFloat(chart.Total, 64)
			res[index].Total = strconv.FormatFloat(totalFloat, 'f', -1, 64)
			res[index].TotalFormat = SizeFormat(totalFloat*1024, 2)
		}
	}

	redisData, _ := json.Marshal(res)
	_, _ = redis.Set(cacheKey, redisData, TimeFormatMin*5)

	return
}
